package com.miaomiao.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miaomiao.common.Result;
import com.miaomiao.domain.system.ChangePwdBody;
import com.miaomiao.domain.system.User;
import com.miaomiao.exception.ServiceException;
import com.miaomiao.mapper.system.UserMapper;
import com.miaomiao.service.system.UserService;
import com.miaomiao.utils.RsaUtils;
import com.miaomiao.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public boolean addUser(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,user.getUserName());
        Integer count = userMapper.selectCount(queryWrapper);
        if(count == 0){
            queryWrapper.clear();
            queryWrapper.eq(User::getEmail,user.getEmail());
            count = userMapper.selectCount(queryWrapper);
            if(count == 0){
                try {
                    user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
                    userMapper.insert(user);
                }catch (Exception e){
                    e.printStackTrace();
                    return false;
                }
                return true;
            }else{
                throw new RuntimeException("邮箱已存在，新增失败！");
            }
        }else{
            throw new RuntimeException("用户名已存在，新增失败！");
        }
    }

    @Override
    public List<User> getAll() {
        userMapper.selectList(null);
        return null;
    }

    @Override
    public Result getPage(int currentPage, int pageSize,String filterName,String state) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if(state != null && state != "") {
            if ("username".equals(filterName)) {
                queryWrapper.eq(User::getUserName, state);
            } else if ("realName".equals(filterName)) {
                queryWrapper.eq(User::getRealName, state);
            } else if ("email".equals(filterName)) {
                queryWrapper.eq(User::getEmail, state);
            } else if ("phone".equals(filterName)) {
                queryWrapper.eq(User::getTelephone, state);
            } else if ("stuId".equals(filterName)) {
                queryWrapper.like(User::getStuId, state);
            }
        }
        Page<User> page = new Page<>(currentPage,pageSize);
        try {
            userMapper.selectPage(page,queryWrapper);
        }catch (Exception e){
            return Result.error("服务错误！");
        }
        List<User> records = page.getRecords().stream().map((user)->{
            user.setPassword("***");
            return user;
        }).collect(Collectors.toList());
        page.setRecords(records);
        return Result.success(page);
    }

    @Override
    public Result changePassword(ChangePwdBody changePwdBody) {
        try{
            changePwdBody.setOldPassword(RsaUtils.decryptByPrivateKey(changePwdBody.getOldPassword()));
            changePwdBody.setNewPassword(RsaUtils.decryptByPrivateKey(changePwdBody.getNewPassword()));
            changePwdBody.setConfirmPassword(RsaUtils.decryptByPrivateKey(changePwdBody.getConfirmPassword()));
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("密码解析错误！");
        }
        if(Objects.isNull(changePwdBody.getNewPassword())
                && Objects.isNull(changePwdBody.getConfirmPassword())
                && !changePwdBody.getNewPassword().equals(changePwdBody.getConfirmPassword())){
            return Result.error("两次密码输入不一致！");
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserId, SecurityUtils.getUserId());
        User user = getOne(queryWrapper);
        if(Objects.isNull(user) && !SecurityUtils.matchesPassword(changePwdBody.getOldPassword(),user.getPassword())){
            return Result.error("旧密码与原密码不一致！");
        }
        User newUser = new User();
        newUser.setPassword(SecurityUtils.encryptPassword(changePwdBody.getNewPassword()));
        update(newUser,queryWrapper);
        return Result.success("修改密码成功");
    }
}
